<template>
  <div>
    <el-card class="box-card">
      <!-- 添加品牌按钮 -->
      <el-button type="primary" icon="Plus" @click="addTrademake">
        添加品牌
      </el-button>
      <!-- 表格 -->
      <el-table :data="trademakeArr" border style="margin: 10px 0px">
        <el-table-column
          prop="序号"
          label="序号"
          width="80"
          align="center"
          type="index"
        />
        <el-table-column prop="tmName" label="品牌名称" width="80" />
        <el-table-column label="品牌LOGO">
          <template #default="scope">
            <img :src="scope.row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademake(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}吗?`"
              width="250px"
              icon="Delete"
              @confirm="removeTradeMark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @current-change="getHasTrademake"
        @size-change="getHasTrademake"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total,"
        :total="total"
      />
    </el-card>
    <!-- 对话框弹出 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademakeParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademakeParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademakeParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademakeParams.logoUrl"
              :src="trademakeParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type UploadProps } from 'element-plus'
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  reqHasTrademake,
  reqAddorUpdateTrademake,
  reqDeleteTrademake,
} from '@/services/product/trademark'
import {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/services/product/trademark/type'
import { ca } from 'element-plus/es/locale/index.mjs'

// 当前页面
let pageNo = ref<number>(1)
// 每页条数
let limit = ref<number>(3)
// 总条数
let total = ref<number>(0)
let trademakeArr = ref<Records>([])
const getHasTrademake = async (pager = 1) => {
  console.log('我触发了');
  pageNo.value = pager
  const res: TradeMarkResponseData = await reqHasTrademake(
    pageNo.value,
    limit.value,
  )
  console.log(res);
  if (res.code == 200) {
    total.value = res.data.total
    trademakeArr.value = res.data.records
  }
}

// 对话框的显示与隐藏
const dialogFormVisible = ref(false)
// 收集新增品牌数据
let trademakeParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})

// 添加品牌
const addTrademake = () => {
  // 先清空
  trademakeParams.tmName = ''
  trademakeParams.logoUrl = ''
  trademakeParams.id = 0
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

// 修改已有品牌
const updateTrademake = (row: TradeMark) => {
  // 清空校验规则合并信息
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })

  dialogFormVisible.value = true
  // 合并对象语法
  Object.assign(trademakeParams, row)
}

// 取消
const cancel = () => {
  dialogFormVisible.value = false
}

// 确定
const confirm = async () => {
  // 发请求前，对整个表单进行校验
  await formRef.value.validate()

  const res: any = await reqAddorUpdateTrademake(trademakeParams)
  if (res.code == 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademakeParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    // 再次获取全部数据，刷新数据
    getHasTrademake(trademakeParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademakeParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    dialogFormVisible.value = false
  }
}

// 上传图片组件-上传文件之前触发
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 上传文件之前触发
  // 限制类型和大小
  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpge' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件小于4M',
      })
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式必须是PNG/JPG/GIF',
    })
  }
}

// 文件上传成功时的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademakeParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}

// 品牌校验自定义方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  console.log(value)
  // 自定义校验规则
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}

// 品牌LOGO图片自定义校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片不能为空！'))
  }
}

// 表单校验规则
const rules = {
  // required必填  trigger:触发校验时机
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, trigger: 'blur', validator: validatorLogoUrl }],
}

// 获取el-form组件实例
const formRef = ref()

// 气泡确认框确认
const removeTradeMark = async (id: number) => {
  // 点击删除已有品牌
  const res = await reqDeleteTrademake(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    getHasTrademake(
      trademakeArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
onMounted(() => {
  getHasTrademake()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
